import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  NativeModules,
  TouchableOpacity,
  Text,
  StyleSheet,
} from 'react-native';
import {
  ActivityIndicator,
  NoticeBar,
  Button,
  Modal,
  Toast,
} from '@ant-design/react-native';
import ApiClient from '@/services/apiClient';
import { WebView } from 'react-native-webview';
import LoginStore from '@/stores/loginStore';
import UserStore from '@/stores/userStore';
import { JC_BASEURL } from '@/constants';
import GatherEditModal from './gatherItemEditModal';
import JobCloseModal from './maintainJobClose';
import PromptRiskPage from './PromptRiskPage';

const styles = StyleSheet.create({
  flex1: { flex: 1 },
  refreshBtn: {
    backgroundColor: '#ebedf0',
    paddingHorizontal: 10,
    borderRadius: 5,
    paddingVertical: 5,
    borderWidth: 0,
    margin: 5,
  },
  stepSignBtn: { backgroundColor: '#BFF3FF' },
});

function JobCardReportView({ navigation, route }) {
  const [isLandscape, setLandscape] = useState(false);
  const onLayout = (e) => {
    const { x, y, width, height } = e.nativeEvent.layout;
    setLandscape(height + y < width + x);
  };
  const webviewRef = useRef();
  const gatherEditPayload = useRef({});
  const [signing, setSigning] = useState(false);
  const [disabled, setDisabled] = useState(true);
  const loginStore = LoginStore.useStore();
  const userStore = UserStore.useStore();
  useEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={handleRefresh} style={styles.refreshBtn}>
          <Text>刷新</Text>
        </TouchableOpacity>
      ),
    });
  }, [navigation]);
  const accToken = loginStore.tokenRefreshTime.access_token;
  /** @type {{ id: number, acno: string, jobCard: string, jobCardUrl: string, taskPaperType: string, cardTitle: string,
    workOrder: string,
    planDate: date,
    finishDate: date,
    airport: string,
    planStatus: string,
    ifMain: number,
    orderType: string,
    taskStageTid: string,
    flightTid: string,
    itemNo: string }} */
  const jcParams = route.params;
  const source = {
    //uri: `${JC_BASEURL}/EM/JobCard/AirlineJobCardReport.aspx?tid=3105691995450202&acno=B-1676&airport=HRB&access_token=${accToken}`,
    uri: `${JC_BASEURL}${jcParams.jobCardUrl}&access_token=${accToken}`,
  };
  console.log(source.uri);
  const injectedRunJs = `(function(){
    // https://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements
    // $(document).on('DOMNodeInserted', selector, function () {
  //setTimeout(function () {
    var iframeContent = $('iframe').contents();
    var iframeWindow = $('iframe')[0].contentWindow;
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '.ant-checkbox-wrapper { box-sizing: border-box; margin: 0; padding: 0; color: rgba(0,0,0,.85); font-size: 18px; font-variant: tabular-nums; line-height: 1.5715; list-style: none; font-feature-settings: "tnum"; display: inline-block; line-height: unset; cursor: pointer;}'
  + '.ant-checkbox+span { color: #108ee9 }'
  + '.ant-checkbox { box-sizing: border-box; margin: 0; padding: 0; color: rgba(0,0,0,.85); font-size: 16px; font-variant: tabular-nums;line-height: 1.5715; list-style: none; font-feature-settings: "tnum"; position: relative; top: -.09em; display: inline-block;line-height: 1; white-space: nowrap; vertical-align: middle; outline: none; cursor: pointer;}'
  + '.ant-checkbox-input { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1; width: 100%; height: 100%;cursor: pointer; opacity: 0;}'
  + 'input[type=checkbox] {  box-sizing: border-box; padding: 0; }'
  + '.ant-checkbox-checked .ant-checkbox-inner { background-color: #1890ff; border-color: #1890ff; }'
  + '.ant-checkbox-inner {  position: relative; top: 0; left: 0; display: block; width: 19px; height: 19px; direction: ltr; background-color: #fff;  border: 1px solid #d9d9d9; border-radius: 2px; border-collapse: separate; transition: all .3s;}'
  + '.ant-checkbox-inner:after {  position: absolute; top: 50%; left: 22%; display: table; width: 5.71428571px; height: 9.14285714px;  border: 2px solid #fff; border-top: 0; border-left: 0; transform: rotate(45deg) scale(0) translate(-50%,-50%); opacity: 0; transition: all .1s cubic-bezier(.71,-.46,.88,.6),opacity .1s; content: " ";}'
  + '.ant-checkbox-checked .ant-checkbox-inner:after {  position: absolute; display: table; border: 2px solid #fff; border-top: 0; border-left: 0; transform: rotate(45deg) scale(1) translate(-50%,-50%); opacity: 1; transition: all .2s cubic-bezier(.12,.4,.29,1.46) .1s;  content: " ";}'
  + '.ant-checkbox-checked:after {  position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 1px solid #1890ff; border-radius: 2px;  visibility: hidden; animation: antCheckboxEffect .36s ease-in-out; animation-fill-mode: backwards; content: "";}';
    iframeContent.find('head')[0].appendChild(style);
    function addSignCheck(signOne) {
      var sigelemId = String(signOne.id);
      var sigelem = iframeContent.find('#' + sigelemId);
      var fatherDiv = iframeContent.find('#' + sigelemId).closest('.flex');
      var nextNum = iframeContent.find('#' + sigelemId).next();
      if (sigelem.length) {
	      //sigelem.css('height', 'auto');
        var sigelemSpanId = sigelemId + 'span';
        var sigelemCheckId = sigelemId + 'chk';
	      var sigelemLabel = sigelemId + 'lbl';
        sigelem.attr('onclick', null);
        sigelem.prepend('<label class="ant-checkbox-wrapper" id="' + sigelemLabel + '"><span class="ant-checkbox" id="' +sigelemSpanId + '"><input type="checkbox" class="ant-checkbox-input" value="" id="' + sigelemCheckId + '"><span class="ant-checkbox-inner"></span></span><span>电签</span></label>');
        // 动态创建element 在原有div id绑定click事件
        sigelem.on('click', '#' + sigelemCheckId, function (ev) {
          var signline = iframeContent.find('#' + sigelemLabel).closest('.flex').find(".ant-checkbox-input");
          var numSpan = iframeContent.find('#' + sigelemLabel).closest('.flex').find('.signline').next();
          if (ev.target.checked) { 
            iframeContent.find('#' + sigelemSpanId).addClass('ant-checkbox-checked');
            signline.each(function(){
              if(signline.length !== 1){
               iframeContent.find(this).attr("id") === sigelemCheckId ? ''
               : iframeContent.find(this).attr("checked") === "checked" ?  (fatherDiv.css('background','#ffd700'),nextNum.css('color','#ffd700'),numSpan.css('color','#ffd700')):''
              }else{
                fatherDiv.css('background','#ffd700');nextNum.css('color','#ffd700');
              }
            })
            window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'checksign', payload: { keyword: sigelemId , itemRelaIds:signOne.itemRelaIds !== undefined?signOne.itemRelaIds:''}}));
          } else{
            fatherDiv.css('background','');
            nextNum.css('color','#fff');
            numSpan.css('color','#fff');
            iframeContent.find('#' + sigelemSpanId).removeClass('ant-checkbox-checked');
            window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'unchecksign', payload: { keyword: sigelemId , itemRelaIds:signOne.itemRelaIds !== undefined?signOne.itemRelaIds:''}}));
          }   
        })
        // window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'unfinished'}));
      }
    }
    function addPTagClick(signOne) {
      var pTagId = '#' + signOne.id;
      console.log(iframeContent.find(pTagId), pTagId);
      if (!iframeContent.find(pTagId).length) {
        return;
      }
    // ios add active class
    //iframeContent.find(pTagId).css('cursor', 'pointer');
    iframeContent.find(pTagId).css('color', '#108ee9');
    //iframeContent.find(pTagId).css('width', 'fit-content');
    //iframeContent.find(pTagId).css('border', '1px solid #bbb');
    iframeContent.find(pTagId).on('click', function (ev) {
           ev.preventDefault();
      ev.stopPropagation();
   
      var payload = {
        type: signOne.type,
        siginRelaIds:signOne.siginRelaIds,
        elementId: pTagId,
        textNodes: [],
        editText: '',
        options: [],
        backgroundColor: $(this).css('background-color')
      }
      $(this).css('background-color', 'antiquewhite');
      $(this).contents().each(function () {
        if (this.nodeType === Node.TEXT_NODE) {
          payload.textNodes.push(this.textContent || this.innerText || '');
        }
      });
      if (signOne.type === 'text') {
        payload.editText = $(this).find('input').attr('value');
      }
      if (signOne.option && signOne.option.map) {
        if (signOne.type === 'radio' || signOne.type === 'checkbox') {
          payload.options = signOne.option.map(function (opt) {
            var checked = !!(iframeContent.find('#' + opt.value).attr('checked'));
            return ({
              value: opt.value,
              label: opt.text,
              checked: checked
            })
          });
        } else if (signOne.type === 'select') {
          var selVal = $(this).find('select').attr('value');
          $(this).find('select').attr('disabled', true);
          payload.options = signOne.option.map(function (opt) {
            return ({
              value: opt.value,
              label: opt.text,
              checked: opt.value === selVal
            })
          });
        }
      }
      window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'edit', payload: payload }));
    });

    }

    function addTipClick(sigelemId){
      var iframeContent = $('iframe').contents();
      var iframeWindow = $('iframe')[0].contentWindow;
      var sigelem = iframeContent.find('#' + sigelemId);
      sigelem.find('a').attr('onclick', null);
      if (sigelem.length) {
	      //sigelem.css('height', 'auto');
        var sigelemSpanId = sigelemId + 'span';
        var sigelemCheckId = sigelemId + 'chk';
	      var sigelemLabel = sigelemId + 'lbl';
        sigelem.attr('onclick', null);
        sigelem.on('click',  function (ev) {
          ev.preventDefault();
          ev.stopPropagation();
          var payload = {
            jcStepId:sigelemId,
          }
            window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'tip' , payload: payload  }));
        });
      }
    }
    iframeWindow.SIGNDATA.length === 0 ? window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'finished' })) : '';
    var buttonTotal=0;
    for (var i = 0; i < iframeWindow.SIGNDATA.length; i++) {
      var signOne = iframeWindow.SIGNDATA[i];
       if (signOne.type === 'button') {
        buttonTotal++;
        addSignCheck(signOne);
      } else if (signOne.type === 'tip') {
        addTipClick(String(signOne.id));
      } else {
        addPTagClick(signOne);
      }
      buttonTotal === 0
        ? window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'finished' }))
        : window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'unfinished' }));
    }
  //}, 100);

})()`;
  const gatherEditModalRef = useRef();
  const closeModalRef = useRef();
  const [stepSign, setStepSign] = useState({
    keywords: [],
    itemRelaIds: [],
  });
  const handleRefresh = () => {
    setStepSign({ ...stepSign, keywords: [], itemRelaIds: [] });
    webviewRef.current.reload();
  };
  const handleSign = async (signKwInfos, metric, finished) => {
    if (!Array.isArray(signKwInfos.keywords) || !signKwInfos.keywords.length) {
      Modal.alert('签署错误', '未设置签署关键字');
      return;
    }

    let signerName = userStore.user.Name;
    const alphaRegex = /^[A-Za-z]+$/;
    if (!signerName || alphaRegex.test(signerName)) {
      // 电子签名人必须是中文, 有字母不行
      //signerName = '无名氏';
      Modal.alert('签署错误', '签名人必须为中文名');
      return;
    }
    signerName = signerName.replace(/[0-9]+/g, '');
    try {
      const {
        signEncs: genEncs,
        signImgBase64,
      } = await NativeModules.XssSigner.showSignatureDialog(
        String(jcParams.id), //businessId
        signerName,
        // userStore.idCardNum.IdCard, // signerIdCard
        '152825199709262726',
        signKwInfos.keywords,
        '123456789', // channel,
        metric || {
          xoffset: 0, // 相对keywords 横向偏移
          yoffset: 15, // 相对keywords 纵向偏移
          imageWidth: 45, // 签名图片宽度
          imageHeight: 30, // 签名图片高度
        },
        isLandscape,
      );

      // 加密包存成文件，上传文件服务器，获取文件地址
      // const formData = [];
      // const uploadRes = [];
      // const EncryptPaths = [];
      // const docs = [];
      // const path = [];
      // for (let i = 0; i < signKwInfos.keywords.length; i++) {
      //   docs[i] =
      //     RNFS.DocumentDirectoryPath + '/' + signKwInfos.keywords[i] + '.txt';
      //   path[i] = (Platform.OS === 'ios' ? '' : 'file://') + docs[i];
      //   RNFS.writeFile(path[i], genEncs[i], 'utf8')
      //     .then(async (success) => {
      //       formData[i] = new FormData();
      //       const fields = {
      //         AppId: appId,
      //         PlateId: 'Plate',
      //         UserId: userStore.user.UserId,
      //         KeyWords: '',
      //         FileDesc: '',
      //       };
      //       Object.keys(fields).forEach((key) => {
      //         formData[i].append(key, fields[key]);
      //       });
      //       if (Array.isArray(genEncs)) {
      //         formData[i].append('filedata', {
      //           uri: path[i],
      //           type: 'plain/text', // android without this network error
      //           name: signKwInfos.keywords[i].concat('.txt'),
      //         });
      //         uploadRes[i] = await ApiClient.post(
      //           'http://fileservice.loongair.cn/FileHandler/FileUploadHandler2.aspx',
      //           formData[i],
      //         );
      //         EncryptPaths[i] =
      //           'http://fileservice.loongair.cn' +
      //           JSON.parse(uploadRes[i].data).FilePath;
      //       }
      //     })
      //     .catch((err) => {
      //       console.log(err.message);
      //     });
      // }
      // console.log('EncryptPaths', EncryptPaths);
      if (Array.isArray(genEncs)) {
        const res = await ApiClient.post('jcSignInfo/v1/doSaveBatch', {
          jcTaskId: jcParams.id,
          jcSignerName: signerName,
          jcSignRelaItemIds: signKwInfos.itemRelaIds,
          jcCardStepIds: signKwInfos.keywords,
          jcSignEncrypts: genEncs,
          // jcEncryptPackagePaths: EncryptPaths,
          jcCardStepflag: finished ? 0 : 1,
        });
        if (res.errorCode) {
          Toast.fail(res.errorMsg);
          return;
        }
      }
      return signImgBase64;
    } catch (err) {
      console.log('sign exception', err);
      Toast.fail(err.message);
    }
  };
  const handleWebViewNavigationStateChange = (newNavState) => {
    if (newNavState.url.indexOf('Login.aspx') !== -1) {
      //LogoutPrompt();
    }
  };

  return (
    <>
      <View style={styles.flex1} onLayout={onLayout}>
        <WebView
          sharedCookiesEnabled={true}
          ref={(ref) => (webviewRef.current = ref)}
          source={source}
          style={styles.flex1}
          originWhitelist={['*']}
          javaScriptEnabled={true}
          onLoadEnd={() => {
            setTimeout(() => {
              if (webviewRef.current) {
                webviewRef.current.injectJavaScript(injectedRunJs);
              }
            }, 100);
          }}
          onNavigationStateChange={handleWebViewNavigationStateChange}
          startInLoadingState={true}
          renderLoading={() => <ActivityIndicator size="large" />}
          renderError={(errorName, errorCode, errorDesc) => (
            <NoticeBar mode="closable" icon={undefined}>
              {errorCode} {errorName}: {errorDesc}
            </NoticeBar>
          )}
          onMessage={async (ev) => {
            const data = JSON.parse(ev.nativeEvent.data);
            if (data.action === 'checksign') {
              setStepSign({
                keywords: stepSign.keywords.concat(data.payload.keyword),
                itemRelaIds: stepSign.itemRelaIds.concat(
                  data.payload.itemRelaIds === ''
                    ? data.payload.itemRelaIds
                    : data.payload.itemRelaIds.join(','),
                ),
              });
            } else if (data.action === 'unchecksign') {
              const itemIds = [...stepSign.itemRelaIds];
              itemIds.splice(
                stepSign.keywords.indexOf(data.payload.keyword),
                1,
              );
              setStepSign({
                keywords: stepSign.keywords.filter(
                  (ssk) => ssk !== data.payload.keyword,
                ),
                itemRelaIds: itemIds,
              });
            } else if (data.action === 'log') {
              console.log(data.payload);
            } else if (data.action === 'finished') {
              setDisabled(false);
            } else if (data.action === 'unfinished') {
              setDisabled(true);
            } else if (data.action === 'tip') {
              navigation.navigate(PromptRiskPage.routeName, {
                id: data.payload.jcStepId.split('-'),
              });
            } else {
              gatherEditPayload.current = data.payload;
              gatherEditModalRef.current.show(
                data.payload.textNodes,
                data.payload.type,
                data.payload.options,
                data.payload.editText,
                data.payload.siginRelaIds,
              );
            }
          }}
        />
      </View>
      <GatherEditModal
        ref={gatherEditModalRef}
        onOk={async (editResults) => {
          let fillElementValueCmd;
          const {
            textNodes,
            elementId,
            siginRelaIds,
            type: editType,
            backgroundColor,
          } = gatherEditPayload.current;
          if (editType === 'select') {
            // https://stackoverflow.com/questions/4680075/set-selected-option-of-select-box
            fillElementValueCmd = `$('iframe').contents().find('${elementId}').find('select').attr('value', '${editResults[0].value}'); `;
          } else if (editType === 'radio' || editType === 'checkbox') {
            // https://stackoverflow.com/questions/871063/how-to-set-radio-option-checked-onload-with-jquery
            fillElementValueCmd = editResults
              .map(
                (edr) =>
                  `$('iframe').contents().find('#'+'${
                    edr.value
                  }').attr('checked', ${!!edr.checked})`,
              )
              .join(';');
          } else {
            fillElementValueCmd = `
              var elem = $('iframe').contents().find('${elementId}').find('input');
              if (elem.length) {
                elem.attr('value', '${editResults}');
              }
            `;
          }
          webviewRef.current.injectJavaScript(`
             var ptag = $('iframe').contents().find('${elementId}');
             ${fillElementValueCmd}
             ptag.css('background-color', '${backgroundColor}');
             //window.ReactNativeWebView.postMessage(JSON.stringify({ action: 'log', payload: JSON.stringify(ptag.html()) }));
             true;
          `);
          const res = await ApiClient.post('jcReceiptList/v1/doSave', {
            jcNumber: jcParams.jobCard,
            jcTaskId: jcParams.id,
            jcAirNumber: jcParams.acno,
            jcSite: jcParams.airport,
            jcImplementerUser: userStore.user.LoginName,
            jcReceiptId: elementId.slice(1),
            jcReceiptTitle: textNodes[0],
            jcSignRelaStepId: siginRelaIds.join(','),
            jcReceiptContent: Array.isArray(editResults)
              ? editResults
                  .filter((edr) => edr.checked)
                  .map((edr) => edr.value)
                  .join(',')
              : editResults,
          });
          if (res.errorMsg) {
            Toast.fail(res.errorMsg);
            return;
          }
        }}
        onCancel={() => {
          const { elementId, backgroundColor } = gatherEditPayload.current;
          webviewRef.current.injectJavaScript(`
             $('iframe').contents().find('${elementId}').css('background-color', '${backgroundColor}');
             true;
          `);
        }}
      />
      <JobCloseModal
        fromSign
        ref={closeModalRef}
        onSubmit={async (signing) => {
          if (signing) {
            const signRes = await handleSign(
              { keywords: ['完工签署'], itemRelaIds: [''] },
              {
                xoffset: 60,
                yoffset: 10,
                imageHeight: 40,
                imageWidth: 60,
              },
              true,
            );
            return signRes;
          }
          navigation.goBack();
        }}
      />

      {stepSign.keywords.length ? (
        <Button
          type="ghost"
          loading={signing}
          style={styles.stepSignBtn}
          onPress={async () => {
            if (stepSign.keywords.length) {
              setSigning(true);
              let signImgBase64 = await handleSign(stepSign);
              if (signImgBase64) {
                signImgBase64 = signImgBase64.replace(/(\r|\n|\r\n)/gm, '');
                for (let i = 0; i < stepSign.keywords.length; i++) {
                  const keyid = stepSign.keywords[i];
                  // 签字成功后签署线添加显示签名图片, 去掉checkbox
                  webviewRef.current.injectJavaScript(`
                    var signode = $('iframe').contents().find('#' + '${keyid}');
                    signode.find('#' + '${keyid}' + 'lbl').remove();
                    signode.prepend('<img style="width: 60px; height: 60px;" src="data:image/png;base64,' + '${signImgBase64}' + '"></img>');
                    true;
                  `);
                }
                setStepSign({ keywords: [] });
              }
              setSigning(false);
            }
            handleRefresh();
          }}
        >
          步骤签署
        </Button>
      ) : (
        <Button
          disabled={disabled}
          type="primary"
          onPress={() => {
            closeModalRef.current.show(jcParams);
          }}
        >
          完工签署
        </Button>
      )}
    </>
  );
}

JobCardReportView.permission = 'Unimplemented';
JobCardReportView.routeName = 'JobCardReportView';
export default JobCardReportView;
